(function() {
 
	var appTree = $("#appTree")
		, unitUrl = '/public/unitof/';

	var getTreeInfo = function () {
		$.get(keter.context + unitUrl + '1', function (data) {
			var setting = {
				view: {
					addHoverDom: addHoverDom
					, removeHoverDom: removeHoverDom
					, selectedMulti: false
				}
				, async: {
					enable: true
					, url : keter.context + unitUrl
					, autoParam:["id"]
				}
				, edit: {
					enable: true
				}
				, callback : {
					onClick : treeNodeClick
					, beforeRemove: beforeRemove
					, beforeRename: beforeRename
				}
			};
			$.fn.zTree.init(appTree, setting, data);
		});
	};

	// 节点点击事件
	function treeNodeClick (e, treeId, treeNode, clickFlag) {
		stopBubble(e);
		var level = treeNode.level,
			parentNode = treeNode.getParentNode();
	}

function beforeRemove(treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj('appTree');
	zTree.selectNode(treeNode);
	return confirm("确认删除 节点 -- " + treeNode.name + " 吗？");
}		
function beforeRename(treeId, treeNode, newName) {
	if (newName.length == 0) {
		alert("节点名称不能为空.");
		return false;
	}
	return true;
}

var newCount = 1;
function addHoverDom(treeId, treeNode) {
	var sObj = $("#" + treeNode.tId + "_span");
	if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
	var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
		+ "' title='add node' onfocus='this.blur();'></span>";
	sObj.after(addStr);
	console.log("add   " + "#addBtn_"+treeNode.id);
	var btn = $("#addBtn_"+treeNode.tId);
	if (btn) btn.bind("click", function(){
		var zTree = $.fn.zTree.getZTreeObj('appTree');
		zTree.addNodes(treeNode, {id:(100 + newCount), pId:treeNode.id, name:"new node" + (newCount++)});
		return false;
	});
};
function removeHoverDom(treeId, treeNode) {
	console.log("remove   " + "#addBtn_"+treeNode.id);
	$("#addBtn_"+treeNode.tId).unbind().remove();
};

	var main = function () {
		getTreeInfo();
	};
	return main();
})();
